import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Space,
  Button,
  Input,
  Select,
  DatePicker,
  Tag,
  Modal,
  Descriptions,
  Image,
  Row,
  Col,
  Statistic,
  message,
  Tooltip,
  Popconfirm
} from 'antd';
import {
  SearchOutlined,
  ReloadOutlined,
  ExportOutlined,
  EyeOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  WarningOutlined,
  CloseCircleOutlined,
  EnvironmentOutlined,
  ToolOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Option } = Select;

// 报警数据接口
interface AlarmData {
  id: string;
  title: string;
  level: 'low' | 'medium' | 'high' | 'critical';
  status: 'pending' | 'processing' | 'resolved' | 'ignored';
  type: 'elevator' | 'hvac' | 'security' | 'fire' | 'access' | 'lighting' | 'system';
  buildingId: string;
  buildingName: string;
  deviceId: string;
  deviceName: string;
  location: string;
  description: string;
  createTime: string;
  updateTime: string;
  resolveTime?: string;
  handler?: string;
  imageUrl?: string;
  priority: number;
}

// 模拟报警数据
const mockAlarmData: AlarmData[] = [
  {
    id: 'ALM001',
    title: '电梯C2故障报警',
    level: 'critical',
    status: 'pending',
    type: 'elevator',
    buildingId: '3',
    buildingName: '华发新城C座',
    deviceId: 'DEV010',
    deviceName: '高速电梯C2',
    location: '东塔2号梯',
    description: '电梯运行异常，检测到机械故障信号',
    createTime: '2024-03-15 14:30:25',
    updateTime: '2024-03-15 14:30:25',
    imageUrl: 'https://via.placeholder.com/300x200?text=电梯故障现场',
    priority: 1
  },
  {
    id: 'ALM002',
    title: '办公楼D座电梯维护提醒',
    level: 'medium',
    status: 'processing',
    type: 'elevator',
    buildingId: 'P2-O4',
    buildingName: '华发二期办公楼D座',
    deviceId: 'P2-O4-E2',
    deviceName: '高速电梯E2',
    location: 'A座2号梯',
    description: '电梯即将到达维护周期，建议安排保养',
    createTime: '2024-03-15 10:15:30',
    updateTime: '2024-03-15 11:20:15',
    handler: '张工程师',
    priority: 2
  },
  {
    id: 'ALM003',
    title: '商业中心空调系统温度异常',
    level: 'high',
    status: 'pending',
    type: 'hvac',
    buildingId: '4',
    buildingName: '商业中心',
    deviceId: 'DEV014',
    deviceName: '中央空调',
    location: '屋顶机房',
    description: '空调系统检测到温度超出正常范围',
    createTime: '2024-03-15 09:45:12',
    updateTime: '2024-03-15 09:45:12',
    priority: 3
  },
  {
    id: 'ALM004',
    title: '住宅楼5号楼电梯故障',
    level: 'critical',
    status: 'resolved',
    type: 'elevator',
    buildingId: 'P2-R5',
    buildingName: '华发二期住宅楼5号楼',
    deviceId: 'P2-R5-E2',
    deviceName: '客梯E2',
    location: '5号楼东侧',
    description: '电梯门系统故障，已完成维修',
    createTime: '2024-03-14 16:20:45',
    updateTime: '2024-03-15 08:30:20',
    resolveTime: '2024-03-15 08:30:20',
    handler: '李技师',
    priority: 4
  },
  {
    id: 'ALM005',
    title: '安防系统离线报警',
    level: 'high',
    status: 'pending',
    type: 'security',
    buildingId: '3',
    buildingName: '高层公寓',
    deviceId: 'DEV011',
    deviceName: '安防监控',
    location: '全楼监控',
    description: '部分监控摄像头离线，需要检查网络连接',
    createTime: '2024-03-15 07:15:30',
    updateTime: '2024-03-15 07:15:30',
    priority: 5
  },
  {
    id: 'ALM006',
    title: '智能照明系统异常',
    level: 'low',
    status: 'ignored',
    type: 'lighting',
    buildingId: '2',
    buildingName: '商业综合体',
    deviceId: 'DEV008',
    deviceName: '智能照明',
    location: '公共区域',
    description: '部分照明设备响应延迟',
    createTime: '2024-03-14 22:30:15',
    updateTime: '2024-03-15 06:45:20',
    handler: '王电工',
    priority: 6
  },
  {
    id: 'ALM007',
    title: '门禁系统刷卡异常',
    level: 'medium',
    status: 'processing',
    type: 'access',
    buildingId: '1',
    buildingName: '华发新城A座',
    deviceId: 'DEV004',
    deviceName: '门禁系统',
    location: '大堂入口',
    description: '门禁读卡器偶发性识别失败',
    createTime: '2024-03-15 06:00:45',
    updateTime: '2024-03-15 08:15:30',
    handler: '赵管理员',
    priority: 7
  },
  {
    id: 'ALM008',
    title: '消防系统自检报警',
    level: 'high',
    status: 'resolved',
    type: 'fire',
    buildingId: '2',
    buildingName: '商业综合体',
    deviceId: 'DEV007',
    deviceName: '消防系统',
    location: '各楼层',
    description: '消防系统定期自检发现烟感器需要清洁',
    createTime: '2024-03-14 03:00:00',
    updateTime: '2024-03-14 09:30:15',
    resolveTime: '2024-03-14 09:30:15',
    handler: '消防维保公司',
    priority: 8
  }
];

const AlarmList: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [alarmData, setAlarmData] = useState<AlarmData[]>(mockAlarmData);
  const [filteredData, setFilteredData] = useState<AlarmData[]>(mockAlarmData);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedAlarm, setSelectedAlarm] = useState<AlarmData | null>(null);

  // 筛选条件
  const [filters, setFilters] = useState({
    keyword: '',
    level: '',
    status: '',
    type: '',
    building: '',
    dateRange: null as any
  });

  // 统计数据
  const [statistics, setStatistics] = useState({
    total: 0,
    pending: 0,
    processing: 0,
    resolved: 0,
    critical: 0,
    high: 0,
    medium: 0,
    low: 0
  });

  // 计算统计数据
  useEffect(() => {
    const stats = {
      total: filteredData.length,
      pending: filteredData.filter(item => item.status === 'pending').length,
      processing: filteredData.filter(item => item.status === 'processing').length,
      resolved: filteredData.filter(item => item.status === 'resolved').length,
      critical: filteredData.filter(item => item.level === 'critical').length,
      high: filteredData.filter(item => item.level === 'high').length,
      medium: filteredData.filter(item => item.level === 'medium').length,
      low: filteredData.filter(item => item.level === 'low').length,
    };
    setStatistics(stats);
  }, [filteredData]);

  // 筛选数据
  const filterData = () => {
    let filtered = [...alarmData];

    if (filters.keyword) {
      filtered = filtered.filter(item =>
        item.title.toLowerCase().includes(filters.keyword.toLowerCase()) ||
        item.description.toLowerCase().includes(filters.keyword.toLowerCase()) ||
        item.buildingName.toLowerCase().includes(filters.keyword.toLowerCase()) ||
        item.deviceName.toLowerCase().includes(filters.keyword.toLowerCase())
      );
    }

    if (filters.level) {
      filtered = filtered.filter(item => item.level === filters.level);
    }

    if (filters.status) {
      filtered = filtered.filter(item => item.status === filters.status);
    }

    if (filters.type) {
      filtered = filtered.filter(item => item.type === filters.type);
    }

    if (filters.building) {
      filtered = filtered.filter(item => item.buildingId === filters.building);
    }

    if (filters.dateRange && filters.dateRange.length === 2) {
      const [start, end] = filters.dateRange;
      filtered = filtered.filter(item => {
        const createTime = dayjs(item.createTime);
        return createTime.isAfter(start) && createTime.isBefore(end);
      });
    }

    setFilteredData(filtered);
  };

  useEffect(() => {
    filterData();
  }, [filters, alarmData]);

  // 获取等级标签样式
  const getLevelTag = (level: string) => {
    const config = {
      critical: { color: 'red', text: '紧急' },
      high: { color: 'orange', text: '重要' },
      medium: { color: 'blue', text: '一般' },
      low: { color: 'green', text: '轻微' }
    };
    const { color, text } = config[level as keyof typeof config] || config.low;
    return <Tag color={color}>{text}</Tag>;
  };

  // 获取状态标签样式
  const getStatusTag = (status: string) => {
    const config = {
      pending: { color: 'red', text: '待处理', icon: <ExclamationCircleOutlined /> },
      processing: { color: 'orange', text: '处理中', icon: <ToolOutlined /> },
      resolved: { color: 'green', text: '已解决', icon: <CheckCircleOutlined /> },
      ignored: { color: 'gray', text: '已忽略', icon: <CloseCircleOutlined /> }
    };
    const { color, text, icon } = config[status as keyof typeof config] || config.pending;
    return <Tag color={color} icon={icon}>{text}</Tag>;
  };

  // 获取类型标签样式
  const getTypeTag = (type: string) => {
    const config = {
      elevator: { color: 'blue', text: '电梯' },
      hvac: { color: 'cyan', text: '空调' },
      security: { color: 'purple', text: '安防' },
      fire: { color: 'red', text: '消防' },
      access: { color: 'orange', text: '门禁' },
      lighting: { color: 'yellow', text: '照明' },
      system: { color: 'gray', text: '系统' }
    };
    const { color, text } = config[type as keyof typeof config] || config.system;
    return <Tag color={color}>{text}</Tag>;
  };

  // 处理报警
  const handleResolve = async (record: AlarmData) => {
    try {
      setLoading(true);
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const updatedData = alarmData.map(item => 
        item.id === record.id 
          ? { 
              ...item, 
              status: 'resolved' as const, 
              resolveTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
              handler: '系统管理员'
            }
          : item
      );
      setAlarmData(updatedData);
      message.success('报警已处理');
    } catch (error) {
      message.error('处理失败');
    } finally {
      setLoading(false);
    }
  };

  // 忽略报警
  const handleIgnore = async (record: AlarmData) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const updatedData = alarmData.map(item => 
        item.id === record.id 
          ? { 
              ...item, 
              status: 'ignored' as const,
              updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
              handler: '系统管理员'
            }
          : item
      );
      setAlarmData(updatedData);
      message.success('报警已忽略');
    } catch (error) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  // 批量处理
  const handleBatchResolve = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要处理的报警');
      return;
    }

    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      const updatedData = alarmData.map(item => 
        selectedRowKeys.includes(item.id)
          ? { 
              ...item, 
              status: 'resolved' as const,
              resolveTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
              handler: '系统管理员'
            }
          : item
      );
      setAlarmData(updatedData);
      setSelectedRowKeys([]);
      message.success(`已处理 ${selectedRowKeys.length} 条报警`);
    } catch (error) {
      message.error('批量处理失败');
    } finally {
      setLoading(false);
    }
  };

  // 导出数据
  const handleExport = () => {
    message.success('导出功能开发中...');
  };

  // 刷新数据
  const handleRefresh = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      message.success('数据已刷新');
    }, 1000);
  };

  // 查看详情
  const handleViewDetail = (record: AlarmData) => {
    setSelectedAlarm(record);
    setDetailModalVisible(true);
  };

  // 表格列配置
  const columns: ColumnsType<AlarmData> = [
    {
      title: '报警标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      ellipsis: true,
      render: (text, record) => (
        <Tooltip title={text}>
          <Button type="link" onClick={() => handleViewDetail(record)}>
            {text}
          </Button>
        </Tooltip>
      )
    },
    {
      title: '等级',
      dataIndex: 'level',
      key: 'level',
      width: 80,
      render: (level) => getLevelTag(level)
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => getStatusTag(status)
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 80,
      render: (type) => getTypeTag(type)
    },
    {
      title: '楼宇',
      dataIndex: 'buildingName',
      key: 'buildingName',
      width: 150,
      ellipsis: true
    },
    {
      title: '设备',
      dataIndex: 'deviceName',
      key: 'deviceName',
      width: 120,
      ellipsis: true
    },
    {
      title: '位置',
      dataIndex: 'location',
      key: 'location',
      width: 120,
      ellipsis: true,
      render: (text) => (
        <span>
          <EnvironmentOutlined style={{ marginRight: 4 }} />
          {text}
        </span>
      )
    },
    {
      title: '报警时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
      sorter: (a, b) => dayjs(a.createTime).unix() - dayjs(b.createTime).unix()
    },
    {
      title: '处理人',
      dataIndex: 'handler',
      key: 'handler',
      width: 100,
      render: (handler) => handler || '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="primary" 
            size="small" 
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          {record.status === 'pending' && (
            <>
              <Popconfirm
                title="确认处理此报警？"
                onConfirm={() => handleResolve(record)}
                okText="确认"
                cancelText="取消"
              >
                <Button 
                  type="primary" 
                  size="small" 
                  icon={<CheckCircleOutlined />}
                  loading={loading}
                >
                  处理
                </Button>
              </Popconfirm>
              <Popconfirm
                title="确认忽略此报警？"
                onConfirm={() => handleIgnore(record)}
                okText="确认"
                cancelText="取消"
              >
                <Button 
                  size="small" 
                  icon={<CloseCircleOutlined />}
                  loading={loading}
                >
                  忽略
                </Button>
              </Popconfirm>
            </>
          )}
        </Space>
      )
    }
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
    getCheckboxProps: (record: AlarmData) => ({
      disabled: record.status === 'resolved' || record.status === 'ignored',
    }),
  };

  return (
    <div className="alarm-list-container">
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总报警数"
              value={statistics.total}
              valueStyle={{ color: '#1890ff' }}
              prefix={<ExclamationCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="待处理"
              value={statistics.pending}
              valueStyle={{ color: '#ff4d4f' }}
              prefix={<WarningOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="处理中"
              value={statistics.processing}
              valueStyle={{ color: '#fa8c16' }}
              prefix={<ToolOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已解决"
              value={statistics.resolved}
              valueStyle={{ color: '#52c41a' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 筛选区域 */}
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={6}>
            <Input
              placeholder="搜索报警标题、描述、楼宇、设备"
              prefix={<SearchOutlined />}
              value={filters.keyword}
              onChange={(e) => setFilters({ ...filters, keyword: e.target.value })}
              allowClear
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="报警等级"
              value={filters.level}
              onChange={(value) => setFilters({ ...filters, level: value })}
              allowClear
              style={{ width: '100%' }}
            >
              <Option value="critical">紧急</Option>
              <Option value="high">重要</Option>
              <Option value="medium">一般</Option>
              <Option value="low">轻微</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Select
              placeholder="处理状态"
              value={filters.status}
              onChange={(value) => setFilters({ ...filters, status: value })}
              allowClear
              style={{ width: '100%' }}
            >
              <Option value="pending">待处理</Option>
              <Option value="processing">处理中</Option>
              <Option value="resolved">已解决</Option>
              <Option value="ignored">已忽略</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Select
              placeholder="报警类型"
              value={filters.type}
              onChange={(value) => setFilters({ ...filters, type: value })}
              allowClear
              style={{ width: '100%' }}
            >
              <Option value="elevator">电梯</Option>
              <Option value="hvac">空调</Option>
              <Option value="security">安防</Option>
              <Option value="fire">消防</Option>
              <Option value="access">门禁</Option>
              <Option value="lighting">照明</Option>
            </Select>
          </Col>
          <Col span={6}>
            <RangePicker
              placeholder={['开始时间', '结束时间']}
              value={filters.dateRange}
              onChange={(dates) => setFilters({ ...filters, dateRange: dates })}
              style={{ width: '100%' }}
            />
          </Col>
        </Row>
      </Card>

      {/* 操作按钮 */}
      <Card style={{ marginBottom: 16 }}>
        <Space>
          <Button 
            type="primary" 
            icon={<CheckCircleOutlined />}
            onClick={handleBatchResolve}
            disabled={selectedRowKeys.length === 0}
            loading={loading}
          >
            批量处理 ({selectedRowKeys.length})
          </Button>
          <Button icon={<ExportOutlined />} onClick={handleExport}>
            导出数据
          </Button>
          <Button icon={<ReloadOutlined />} onClick={handleRefresh} loading={loading}>
            刷新
          </Button>
        </Space>
      </Card>

      {/* 数据表格 */}
      <Card>
        <Table
          columns={columns}
          dataSource={filteredData}
          rowKey="id"
          loading={loading}
          rowSelection={rowSelection}
          scroll={{ x: 1200 }}
          pagination={{
            total: filteredData.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          }}
        />
      </Card>

      {/* 详情弹窗 */}
      <Modal
        title="报警详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>,
          selectedAlarm?.status === 'pending' && (
            <Button 
              key="resolve" 
              type="primary" 
              onClick={() => {
                if (selectedAlarm) {
                  handleResolve(selectedAlarm);
                  setDetailModalVisible(false);
                }
              }}
              loading={loading}
            >
              处理报警
            </Button>
          )
        ]}
        width={800}
      >
        {selectedAlarm && (
          <div>
            <Descriptions column={2} bordered>
              <Descriptions.Item label="报警标题" span={2}>
                {selectedAlarm.title}
              </Descriptions.Item>
              <Descriptions.Item label="报警等级">
                {getLevelTag(selectedAlarm.level)}
              </Descriptions.Item>
              <Descriptions.Item label="处理状态">
                {getStatusTag(selectedAlarm.status)}
              </Descriptions.Item>
              <Descriptions.Item label="报警类型">
                {getTypeTag(selectedAlarm.type)}
              </Descriptions.Item>
              <Descriptions.Item label="优先级">
                {selectedAlarm.priority}
              </Descriptions.Item>
              <Descriptions.Item label="所属楼宇">
                {selectedAlarm.buildingName}
              </Descriptions.Item>
              <Descriptions.Item label="相关设备">
                {selectedAlarm.deviceName}
              </Descriptions.Item>
              <Descriptions.Item label="设备位置">
                <EnvironmentOutlined style={{ marginRight: 4 }} />
                {selectedAlarm.location}
              </Descriptions.Item>
              <Descriptions.Item label="处理人员">
                {selectedAlarm.handler || '未分配'}
              </Descriptions.Item>
              <Descriptions.Item label="报警时间">
                {selectedAlarm.createTime}
              </Descriptions.Item>
              <Descriptions.Item label="更新时间">
                {selectedAlarm.updateTime}
              </Descriptions.Item>
              {selectedAlarm.resolveTime && (
                <Descriptions.Item label="解决时间">
                  {selectedAlarm.resolveTime}
                </Descriptions.Item>
              )}
              <Descriptions.Item label="详细描述" span={2}>
                {selectedAlarm.description}
              </Descriptions.Item>
            </Descriptions>
            
            {selectedAlarm.imageUrl && (
              <div style={{ marginTop: 16 }}>
                <h4>现场图片：</h4>
                <Image
                  src={selectedAlarm.imageUrl}
                  alt="报警现场"
                  style={{ maxWidth: '100%' }}
                />
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
};

export default AlarmList;